package com.func.infrastructure.persistent.repository;

import com.func.domain.task.model.entity.TaskEntity;
import com.func.domain.task.repository.ITaskRepository;
import com.func.infrastructure.event.EventPublisher;
import com.func.infrastructure.persistent.dao.task.ITaskDao;
import com.func.infrastructure.persistent.po.task.Task;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * TaskRepository
 * </p>
 *
 * @author Simon
 * @version 2025.03.15.1.0.0
 * @description
 * @since 2025-03-15
 */

@Repository
public class TaskRepository implements ITaskRepository {
    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher  eventPublisher;

    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<Task> tasks = taskDao.queryNoSendMessageTaskList();
        List<TaskEntity> taskEntities = new ArrayList<>(tasks.size());

        for (Task task : tasks) {
            TaskEntity taskEntity = TaskEntity.builder()
                        .user_id(task.getUserId())
                        .topic(task.getTopic())
                        .message_id(task.getMessageId())
                        .message(task.getMessage())
                        .build();
            taskEntities.add(taskEntity);
        }
        return taskEntities;
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(task);
    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(task);

    }
}
